package com.icart.api;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.icart.vo.AccessToken;

import net.sf.json.JSONObject;

/**
 * 微信基本接口
 *
 * @Author： [Guobiao.Li@desay-svautomotive.com] on [2017/9/6]
 * Modified By： [修改人] on [修改日期] for [修改说明]
 */
public class WxApi {

    private static final String ACCESS_TOKEN = "aBlqnL_Vl4Ca7a7hZM2HAw668aa-CmR-FgRsJB6shv9xkhO126zLiPAoEtLOupS2xW7Xxi1M7BH8hoQl4AsVQoCg1fEcbrZpPOAUmirXdpLhifFgFcUHSMu6CEfIgcHAWVZjAEAJIM";

    private static final String MENU_STR = "{\"button\":[{\"name\":\"养护服务\",\"sub_button\":[{\"type\":\"click\",\"name\":\"扫一扫\",\"key\":\"scanMenuid\",\"sub_button\":[]},{\"type\":\"click\",\"name\":\"我的订单\",\"key\":\"myorderMenuid\",\"sub_button\":[]},{\"type\":\"click\",\"name\":\"我要预约\",\"key\":\"bookingMenuid\",\"sub_button\":[]},{\"type\":\"click\",\"name\":\"附近门店\",\"key\":\"poiStoreMenuid\",\"sub_button\":[]}]},{\"type\":\"click\",\"name\":\"优惠资讯\",\"key\":\"discountInfoMenuid\",\"sub_button\":[]},{\"type\":\"click\",\"name\":\"个人中心\",\"key\":\"userInfoMenuid\",\"sub_button\":[{\"type\":\"view\",\"name\":\"搜索\",\"url\":\"http://wechat.nat123.cc/index.html\"}]}]}";

    //token 接口
    private static final String TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    //创建菜单
    private static final String MENU_CREATE = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s";

    //查询菜单
    private static final String MENU_QUERY = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s";

    //删除菜单
    private static final String MENU_DELETE = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s";

    /**
     * 获取Token接口
     *
     * @param appId
     * @param appSecret
     * @return
     */
    public static String getTokenUrl(String appId, String appSecret) {
        return String.format(TOKEN, appId, appSecret);
    }

    //获取菜单创建接口
    public static String getMenuCreateUrl(String token) {
        return String.format(MENU_CREATE, token);
    }

    public static String getMenuQuery(String token) {
        return String.format(MENU_QUERY, token);
    }

    //获取菜单删除接口
    public static String getMenuDeleteUrl(String token) {
        return String.format(MENU_DELETE, token);
    }

    public static void main(String[] args) {
                WxApi.createMenu();
        WxApi.queryMenu();
//                WxApi.deleteMenu();
    }

    public static void queryMenu() {
        String tokenUrl = WxApi.getMenuQuery(ACCESS_TOKEN);
        JSONObject jsonObject = httpsRequest(tokenUrl, HttpMethod.GET, null);
        System.out.println("jsonObject:" + jsonObject);
    }

    public static void deleteMenu() {
        String tokenUrl = WxApi.getMenuDeleteUrl(ACCESS_TOKEN);
        JSONObject jsonObject = httpsRequest(tokenUrl, HttpMethod.GET, null);
        System.out.println("jsonObject:" + jsonObject);
    }

    public static void createMenu() {
        String tokenUrl = WxApi.getMenuCreateUrl(ACCESS_TOKEN);
        JSONObject jsonObject = httpsRequest(tokenUrl, HttpMethod.POST, MENU_STR);
        System.out.println("jsonObject:" + jsonObject);
    }

    /**
     * 获取访问凭证
     * 1、grant_type参数可以不要
     */
    public static AccessToken getToken(String appId, String appSecret) {
        AccessToken token = null;
        String tokenUrl = WxApi.getTokenUrl(appId, appSecret);
        JSONObject jsonObject = httpsRequest(tokenUrl, HttpMethod.GET, null);
        if (null != jsonObject && !jsonObject.containsKey("errcode")) {
            token = new AccessToken();
            String access_token = jsonObject.getString("access_token");
            int expires_in = jsonObject.getInt("expires_in");
            token.setAccessToken(access_token);
            token.setExpiresIn(expires_in);
            return token;
        } else if (null != jsonObject) {
            String errcode = jsonObject.getString("errcode");
            String errmsg = jsonObject.getString("errmsg");
            token = new AccessToken();
            token.setErrcode(errcode);
            token.setErrmsg(errmsg);
            return token;
        }
        return null;
    }

    /**
     * 处理https请求，返回结果数据
     * 
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            //TrustManager[] tm = {new WeiXinX509TrustManager()};
            TrustManager[] tm = { new WeiXinX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            if (outputStr != null) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
            }
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return jsonObject;
    }
}
